use std::{env, fs, path::PathBuf};

use bindgen::Builder;
use cc::Build;


fn add_device(cc: &mut Build) {
    cc.define("STM32F10X_MD", "")
    .file("./c_src/device/system_stm32f10x.c");
}   

fn add_cmsis_rtos(cc: &mut Build) {
    let path = "./c_src/rtos";
    let mut dir = fs::read_dir(path).unwrap();
    while let Some(Ok(file)) = dir.next() {
        if !file.metadata().unwrap().is_file() {
            continue;
        }
        let name =  file.file_name();
        let name = name.to_str().unwrap();
        if !name.ends_with(".c") {
            continue;
        }
        cc.file(file.path());
    }
    cc.file("./c_src/rtos/GCC/irq_armv7m.S");
}

fn build_src() {
    let mut cc = Build::new();
    cc.include("./c_src/CMSIS");
    cc.include("./c_src/device");
    cc.include("./c_src/rtos");
    add_device(&mut cc);
    add_cmsis_rtos(&mut cc);
    cc.compile("cmsis_rtos2");
}

fn bind_inc() {
    let path = env::var("OUT_DIR").unwrap();

    Builder::default()
        .use_core()
        .header("./c_src/device/system_stm32f10x.h")
        .header("./c_src/rtos/rtx_os.h")
        .generate().unwrap()
        .write_to_file(PathBuf::from(path).join("cmsis_rtos2.rs"))
        .unwrap();
}

fn main() {
    bind_inc();
    build_src();
}

